package com.licheng.service.imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.licheng.mapper.ClazzMapper;
import com.licheng.pojo.Clazz;
import com.licheng.pojo.ClazzPageQuery;
import com.licheng.pojo.ClazzPageResult;
import com.licheng.pojo.Result;
import com.licheng.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    /**
     * 班级分页查询
     * @param cpq 查询条件
     * @return 返回符合条件的班级
     */
    @Override
    public ClazzPageResult selectClazz(ClazzPageQuery cpq) {
        PageHelper.startPage(cpq.getPage(), cpq.getPageSize());

        List<Clazz> clazzList = clazzMapper.selectClazz(cpq);
        Page p = (Page) clazzList;

        Long total = p.getTotal();
        List<Clazz> rows = p.getResult();
        //对班级状态进行判断
        for (Clazz row : rows) {
            if (row.getBeginDate().isAfter(LocalDate.now())) {
                row.setStatus("未开班");
            } else if (row.getBeginDate().isBefore(LocalDate.now())
                       && row.getEndDate().isAfter(LocalDate.now())) {
                row.setStatus("已开班");
            }else row.setStatus("已结课");
        }
        return new ClazzPageResult(total, rows);
    }

    /**
     * 删除班级
     * @param id 班级id
     */
    @Override
    public Result deleteClazz(Integer id) {
        //先根据id查询该班级下的学生人数
       Integer count =  clazzMapper.selectStudent(id);
        //如果班级有学生的话不能删除
        if(count>0){
           return Result.error("对不起, 该班级下有学生, 不能直接删除");
       }
       clazzMapper.deleteClazz(id);
       return Result.success();
    }

    /**
     * 根据id查询班级
     * @param id
     * @return
     */
    @Override
    public Clazz selectById(Integer id) {
        Clazz clazz = clazzMapper.selectById(id);
        return clazz;
    }

    /**
     * 修改班级
     * @param clazz
     */
    @Override
    public void updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateClazz(clazz);
    }

    /**
     * 查询所有班级
     * @return
     */
    @Override
    public List<Clazz> selectAllStudent() {
        List<Clazz> clazzList = clazzMapper.selectAllStudent();
        return clazzList;
    }

    /**
     * 添加班级
     * @param clazz
     */
    @Override
    public void insertClazz(Clazz clazz) {
        //添加基础信息
        clazz.setUpdateTime(LocalDateTime.now());
        clazz.setCreateTime(LocalDateTime.now());
        clazzMapper.insertClazz(clazz);
    }


}
